Learn in 10 minutes

Learn in 10 minutes

10분 만에 PHP 배우기

PHP는 웹 개발을 위해 설계된 널리 사용되는 서버 사이드 스크립팅 언어입니다. 원래 “개인 홈페이지"를 위해 만들어진 PHP는 이제 “PHP: Hypertext Preprocessor"를 의미합니다. 이 튜토리얼은 PHP 8.3+ 기능을 다루며, 현대적인 PHP 개발을 빠르게 배울 수 있도록 도와줍니다.

1. 첫 번째 PHP 프로그램 작성하기

간단한 프로그램부터 시작해보겠습니다. hello.php라는 파일을 만들고 다음 코드를 입력하세요:

<?php
echo "Hello, World!";
?>

파일을 저장하고 웹 서버나 PHP CLI를 사용해서 실행하세요:

php hello.php

출력 결과는 다음과 같습니다:

Hello, World!

이 간단한 프로그램은 PHP의 기본 출력 기능을 보여줍니다. echo 문은 텍스트를 표시하는 데 사용됩니다. PHP 코드는 <?php?> 태그 안에 포함됩니다.

2. 기본 문법

PHP 문법은 간단하고 C와 Perl과 유사합니다. PHP 코드는 서버에서 실행되고, 결과가 일반 HTML로 브라우저에 전송됩니다.

<?php
// This is a single-line comment
echo "Hello, World!";

/*
This is a multi-line comment
spanning multiple lines
*/
?>

PHP의 기본 문법 규칙:

  • PHP 태그: PHP 코드는 <?php ... ?> 태그로 감싸야 합니다
  • 주석: 한 줄 주석은 // 또는 #을 사용하고, 여러 줄 주석은 /* ... */을 사용합니다
  • 문장: 세미콜론 ;으로 끝납니다
  • 대소문자 구분: 변수명은 대소문자를 구분하지만 함수명은 구분하지 않습니다
  • 변수: $ 기호로 시작합니다
<?php
$name = "John";      // Variable (case-sensitive)
$Name = "Jane";      // Different variable
echo $name;          // Outputs: John
ECHO $Name;          // Outputs: Jane (ECHO works same as echo)
?>

3. 변수와 데이터 타입

PHP에서 변수는 데이터를 저장하는 컨테이너입니다. PHP는 느슨한 타입 언어로, 변수 타입을 명시적으로 선언할 필요가 없습니다.

변수 명명 규칙:

  • $ 기호로 시작해야 합니다
  • 문자, 숫자, 밑줄을 포함할 수 있습니다
  • 숫자로 시작할 수 없습니다
  • 대소문자를 구분합니다

PHP의 주요 데이터 타입:

  • String: 따옴표로 둘러싸인 텍스트 데이터
  • Integer: 정수
  • Float: 소수
  • Boolean: true 또는 false
  • Array: 값들의 집합
  • Object: 클래스의 인스턴스
  • NULL: 값이 없음을 나타냄
  • Resource: 외부 리소스에 대한 참조
<?php
$name = "Alice";           // String
$age = 25;                 // Integer
$height = 5.8;             // Float
$is_student = true;        // Boolean
$grades = [90, 85, 92];    // Array
$data = null;              // NULL

// Type checking
var_dump($name);           // string(5) "Alice"
echo gettype($age);        // integer
?>

3.1 문자열 연산

문자열은 작은따옴표나 큰따옴표를 사용해서 정의할 수 있으며, 서로 다른 동작을 합니다:

<?php
$single = 'Single quote string';
$double = "Double quote string";
$name = "John";
$greeting = "Hello, $name!";        // Variable interpolation
$greeting2 = 'Hello, $name!';       // No interpolation

echo $greeting;   // Hello, John!
echo $greeting2;  // Hello, $name!

// String concatenation
$full_name = "John" . " " . "Doe";
$full_name .= " Jr.";               // Append

// String functions
echo strlen($name);                 // String length: 4
echo strtoupper($name);            // JOHN
echo strtolower($name);            // john
echo substr($name, 0, 2);          // Jo
?>

3.2 배열

PHP는 인덱스 배열, 연관 배열, 다차원 배열을 지원합니다:

<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);

// Associative array
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

// Multidimensional array
$students = [
    ["name" => "Alice", "grade" => 90],
    ["name" => "Bob", "grade" => 85],
    ["name" => "Carol", "grade" => 92]
];

// Accessing arrays
echo $fruits[0];                    // apple
echo $person["name"];               // John
echo $students[0]["grade"];         // 90

// Array functions
echo count($fruits);                // 3
array_push($fruits, "grape");       // Add element
print_r($fruits);                   // Display array
?>

4. 연산자

PHP는 다양한 연산을 위한 여러 연산자를 제공합니다:

4.1 산술 연산자

<?php
$a = 10;
$b = 3;

echo $a + $b;    // Addition: 13
echo $a - $b;    // Subtraction: 7
echo $a * $b;    // Multiplication: 30
echo $a / $b;    // Division: 3.333...
echo $a % $b;    // Modulus: 1
echo $a ** $b;   // Exponentiation: 1000
?>

4.2 비교 연산자

<?php
$x = 5;
$y = "5";

var_dump($x == $y);   // true (equal value)
var_dump($x === $y);  // false (identical type and value)
var_dump($x != $y);   // false
var_dump($x !== $y);  // true
var_dump($x > 3);     // true
var_dump($x <= 5);    // true
?>

4.3 논리 연산자

<?php
$a = true;
$b = false;

var_dump($a && $b);   // false (AND)
var_dump($a || $b);   // true (OR)
var_dump(!$a);        // false (NOT)
var_dump($a and $b);  // false (AND, lower precedence)
var_dump($a or $b);   // true (OR, lower precedence)
?>

5. 제어 흐름

5.1 if 문

<?php
$age = 20;

if ($age >= 18) {
    echo "Adult";
} elseif ($age >= 13) {
    echo "Teen";
} else {
    echo "Child";
}

// Ternary operator
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;

// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>

5.2 switch 문

<?php
$day = "Monday";

switch ($day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        echo "Weekday";
        break;
    case "Saturday":
    case "Sunday":
        echo "Weekend";
        break;
    default:
        echo "Invalid day";
}
?>

5.3 루프

for 루프:

<?php
for ($i = 0; $i < 5; $i++) {
    echo "Number: $i\n";
}

// foreach for arrays
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

// foreach with key-value pairs
$person = ["name" => "John", "age" => 30];
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
?>

while과 do-while 루프:

<?php
$count = 0;
while ($count < 3) {
    echo "Count: $count\n";
    $count++;
}

$num = 0;
do {
    echo "Number: $num\n";
    $num++;
} while ($num < 3);
?>

6. 함수

PHP의 함수는 특정 작업을 수행하는 재사용 가능한 코드 블록입니다:

<?php
// Basic function
function greet($name) {
    return "Hello, $name!";
}

echo greet("Alice");

// Function with default parameters
function calculate_area($length, $width = 1) {
    return $length * $width;
}

echo calculate_area(5);      // 5 (width defaults to 1)
echo calculate_area(5, 3);   // 15

// Variable arguments
function sum(...$numbers) {
    return array_sum($numbers);
}

echo sum(1, 2, 3, 4);        // 10

// Anonymous functions (closures)
$multiply = function($a, $b) {
    return $a * $b;
};

echo $multiply(4, 5);        // 20
?>

6.1 변수 범위

<?php
$global_var = "I'm global";

function test_scope() {
    global $global_var;
    $local_var = "I'm local";

    echo $global_var;        // Accessible with 'global' keyword
    echo $local_var;         // Local to this function
}

test_scope();

// Static variables
function counter() {
    static $count = 0;
    $count++;
    echo "Count: $count\n";
}

counter();  // Count: 1
counter();  // Count: 2
counter();  // Count: 3
?>

7. 객체 지향 프로그래밍

PHP는 클래스와 객체를 사용한 객체 지향 프로그래밍을 지원합니다:

<?php
class Person {
    // Properties
    private $name;
    private $age;
    public $city;

    // Constructor
    public function __construct($name, $age, $city = "Unknown") {
        $this->name = $name;
        $this->age = $age;
        $this->city = $city;
    }

    // Methods
    public function getName() {
        return $this->name;
    }

    public function setAge($age) {
        if ($age > 0) {
            $this->age = $age;
        }
    }

    public function getAge() {
        return $this->age;
    }

    public function introduce() {
        return "Hi, I'm {$this->name}, {$this->age} years old from {$this->city}";
    }
}

// Creating objects
$person1 = new Person("John", 25, "New York");
$person2 = new Person("Jane", 30);

echo $person1->introduce();
echo $person2->getName();
?>

7.1 상속

<?php
class Animal {
    protected $name;
    protected $species;

    public function __construct($name, $species) {
        $this->name = $name;
        $this->species = $species;
    }

    public function makeSound() {
        return "{$this->name} makes a sound";
    }

    public function getInfo() {
        return "{$this->name} is a {$this->species}";
    }
}

class Dog extends Animal {
    private $breed;

    public function __construct($name, $breed) {
        parent::__construct($name, "Dog");
        $this->breed = $breed;
    }

    public function makeSound() {
        return "{$this->name} barks";
    }

    public function fetch() {
        return "{$this->name} fetches the ball";
    }
}

$dog = new Dog("Buddy", "Golden Retriever");
echo $dog->getInfo();      // Buddy is a Dog
echo $dog->makeSound();    // Buddy barks
echo $dog->fetch();        // Buddy fetches the ball
?>

8. 오류 처리

PHP는 오류와 예외를 처리하는 여러 방법을 제공합니다:

<?php
// Try-catch for exceptions
try {
    $result = 10 / 0;
    throw new Exception("Custom error message");
} catch (DivisionByZeroError $e) {
    echo "Division by zero error: " . $e->getMessage();
} catch (Exception $e) {
    echo "General error: " . $e->getMessage();
} finally {
    echo "This always executes";
}

// Custom exception class
class CustomException extends Exception {
    public function errorMessage() {
        return "Custom error on line {$this->getLine()} in {$this->getFile()}: {$this->getMessage()}";
    }
}

try {
    throw new CustomException("Something went wrong!");
} catch (CustomException $e) {
    echo $e->errorMessage();
}
?>

9. 파일 작업

PHP는 파일 조작을 위한 다양한 함수를 제공합니다:

<?php
// Reading files
$content = file_get_contents("example.txt");
echo $content;

// Writing files
file_put_contents("output.txt", "Hello, PHP!");

// File operations with error handling
if (file_exists("data.txt")) {
    $lines = file("data.txt", FILE_IGNORE_NEW_LINES);
    foreach ($lines as $line) {
        echo $line . "\n";
    }
} else {
    echo "File not found";
}

// Working with file handles
$handle = fopen("log.txt", "a");
if ($handle) {
    fwrite($handle, "Log entry: " . date("Y-m-d H:i:s") . "\n");
    fclose($handle);
}
?>

10. 폼과 HTTP 작업

PHP는 웹 폼과 HTTP 요청 처리에 뛰어납니다:

<?php
// HTML form (save as form.html)
/*
<form method="POST" action="process.php">
    <input type="text" name="username" placeholder="Username">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Submit</button>
</form>
*/

// Processing form data (process.php)
if ($_POST) {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';

    // Validation
    if (empty($username) || empty($email) || empty($password)) {
        echo "All fields are required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format";
    } else {
        // Process the data
        echo "Welcome, " . htmlspecialchars($username);
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        // Save to database, etc.
    }
}

// Working with GET parameters
$page = $_GET['page'] ?? 1;
$category = $_GET['category'] ?? 'all';
echo "Page: $page, Category: $category";
?>

11. 데이터베이스 작업

PHP는 일반적으로 데이터베이스, 특히 MySQL과 함께 작업합니다:

<?php
// Database connection using PDO
try {
    $pdo = new PDO(
        "mysql:host=localhost;dbname=mydb;charset=utf8",
        "username",
        "password",
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // Prepared statements (secure)
    $stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND city = ?");
    $stmt->execute([18, "New York"]);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "User: " . $row['name'] . "\n";
    }

    // Insert data
    $stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
    $stmt->execute(["John Doe", "[email protected]", 25]);

    echo "Last inserted ID: " . $pdo->lastInsertId();

} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
}
?>

12. 현대적인 PHP 기능 (PHP 8.0+)

PHP 8.0+는 많은 현대적인 기능을 도입했습니다:

<?php
// Named arguments (PHP 8.0+)
function createUser($name, $email, $age = 18, $active = true) {
    return compact('name', 'email', 'age', 'active');
}

$user = createUser(
    name: "John",
    email: "[email protected]",
    active: false
);

// Match expression (PHP 8.0+)
$status_code = 200;
$message = match($status_code) {
    200, 201 => 'Success',
    400 => 'Bad Request',
    404 => 'Not Found',
    500 => 'Server Error',
    default => 'Unknown Status'
};

// Nullsafe operator (PHP 8.0+)
$user_name = $user?->profile?->name ?? 'Unknown';

// Constructor property promotion (PHP 8.0+)
class User {
    public function __construct(
        public string $name,
        public string $email,
        public int $age = 18,
        private bool $active = true
    ) {}

    public function isActive(): bool {
        return $this->active;
    }
}

$user = new User("John", "[email protected]", 25);
echo $user->name;  // John

// Enums (PHP 8.1+)
enum Status {
    case PENDING;
    case APPROVED;
    case REJECTED;

    public function label(): string {
        return match($this) {
            Status::PENDING => 'Pending',
            Status::APPROVED => 'Approved',
            Status::REJECTED => 'Rejected',
        };
    }
}

$status = Status::PENDING;
echo $status->label();  // Pending
?>

13. 모범 사례와 팁

다음은 중요한 PHP 모범 사례들입니다:

<?php
// 1. Always use PHP opening tags
// Good: <?php
// Avoid: <? (short tags)

// 2. Use prepared statements for database queries
// Prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);

// 3. Validate and sanitize input
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');

// 4. Use meaningful variable names
// Good:
$user_age = 25;
$is_active = true;

// Bad:
$a = 25;
$flag = true;

// 5. Handle errors gracefully
function divide($a, $b) {
    if ($b == 0) {
        throw new InvalidArgumentException("Division by zero");
    }
    return $a / $b;
}

// 6. Use type declarations (PHP 7+)
function calculateTotal(array $items): float {
    return array_sum($items);
}

// 7. Organize code with namespaces
namespace App\Models;

class User {
    // class implementation
}

// 8. Use composer for dependency management
// composer.json example:
/*
{
    "require": {
        "monolog/monolog": "^2.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}
*/
?>

PHP는 웹 개발에 완벽한 강력하고 유연한 언어입니다. 이 튜토리얼은 PHP 애플리케이션 구축을 시작하는 데 필요한 필수 개념들을 다뤘습니다. 이러한 개념들을 연습하고, Laravel이나 Symfony 같은 PHP 프레임워크를 탐색하며 계속 학습하세요!